#include <iostream>
#include <unistd.h>
#include "BlockingQueue.hpp"
#include "Task.hpp"

void *consumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        sleep(1);
        Task t = bq->Pop();
        t.Execute();
        std::cout << "处理了一个任务：" << t.GetA() << "+" << t.GetB() 
                    << "=" << t.Result() << std::endl;
    }
    return nullptr;
}

void *producer(void *args)
{
    int a = 1, b =2;
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        //sleep(1);
        Task t(a, b);
        bq->EQueue(t);
        std::cout << "生产了一个任务：" << a << "+" << b << "=?" << std::endl;
        
        a++, b++;
    }
    return nullptr;
}

int main()
{
    // 申请阻塞队列
    BlockQueue<Task> *bq = new BlockQueue<Task>();

    // 构建生产者消费者关系
    pthread_t c[2], p[3];

    pthread_create(c , nullptr, consumer, bq);
    pthread_create(c + 1, nullptr, consumer, bq);
    pthread_create(p, nullptr, producer, bq);
    pthread_create(p + 1, nullptr, producer, bq);
    pthread_create(p + 2, nullptr, producer, bq);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1] + 1, nullptr);
    pthread_join(p[2] + 2, nullptr);

    return 0;
}